import { authClient } from "@/lib/auth-client";
{{#if (eq api "trpc")}}
import { queryClient } from "@/utils/trpc";
{{/if}}
{{#if (eq api "orpc")}}
import { queryClient } from "@/utils/orpc";
{{/if}}
import { useState } from "react";
import {
ActivityIndicator,
Text,
TextInput,
Pressable,
View,
} from "react-native";
import { Card, useThemeColor } from "heroui-native";

function signUpHandler({
name,
email,
password,
setError,
setIsLoading,
setName,
setEmail,
setPassword,
}) {
setIsLoading(true);
setError(null);

authClient.signUp.email(
{
name,
email,
password,
},
{
onError(error) {
setError(error.error?.message || "Failed to sign up");
setIsLoading(false);
},
onSuccess() {
setName("");
setEmail("");
setPassword("");
{{#if (eq api "orpc")}}
queryClient.refetchQueries();
{{/if}}
{{#if (eq api "trpc")}}
queryClient.refetchQueries();
{{/if}}
},
onFinished() {
setIsLoading(false);
},
}
);
}

export function SignUp() {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

  const mutedColor = useThemeColor("muted");
  const accentColor = useThemeColor("accent");
  const foregroundColor = useThemeColor("foreground");
  const dangerColor = useThemeColor("danger");

  function handlePress() {
  signUpHandler({
  name,
  email,
  password,
  setError,
  setIsLoading,
  setName,
  setEmail,
  setPassword,
  });
  }

  return (
  <Card variant="secondary" className="mt-6 p-4">
    <Card.Title className="mb-4">Create Account</Card.Title>

    {error && (
    <View className="mb-4 p-3 bg-danger/10 rounded-lg">
      <Text className="text-danger text-sm">{error}</Text>
    </View>
    )}

    <TextInput className="mb-3 py-3 px-4 rounded-lg bg-surface text-foreground border border-divider" placeholder="Name"
      value={name} onChangeText={setName} placeholderTextColor={mutedColor} />

    <TextInput className="mb-3 py-3 px-4 rounded-lg bg-surface text-foreground border border-divider"
      placeholder="Email" value={email} onChangeText={setEmail} placeholderTextColor={mutedColor}
      keyboardType="email-address" autoCapitalize="none" />

    <TextInput className="mb-4 py-3 px-4 rounded-lg bg-surface text-foreground border border-divider"
      placeholder="Password" value={password} onChangeText={setPassword} placeholderTextColor={mutedColor}
      secureTextEntry />

    <Pressable onPress={handlePress} disabled={isLoading}
      className="bg-accent p-4 rounded-lg flex-row justify-center items-center active:opacity-70">
      {isLoading ? (
      <ActivityIndicator size="small" color={foregroundColor} />
      ) : (
      <Text className="text-foreground font-medium">Sign Up</Text>
      )}
    </Pressable>
  </Card>
  );
  }